import { Entity, Column, PrimaryGeneratedColumn, BeforeInsert } from 'typeorm';
import { randomAvatar } from '@/utils/randomAvatar';
import { generateRandomName } from '@/utils/randomNickName';
import { Exclude } from 'class-transformer';
import * as bcrypt from 'bcryptjs';

@Entity() // 将这个类定义为一个数据库实体
export class UserEntity {
  @PrimaryGeneratedColumn() // 主键，自动生成id
  user_id: number;

  @Column({ length: 50, unique: true, comment: '用户名' })
  username: string;

  @Column({
    type: 'varchar',
    length: 100,
    comment: '昵称',
    nullable: false,
    default: generateRandomName(), //随机昵称
  })
  // 昵称
  nickname: string;

  @Column({
    type: 'varchar',
    length: 255,
    comment: '头像URL',
    default: randomAvatar(), //随机头像
    nullable: false,
  })
  avatar_url: string;

  @Exclude()
  @Column({
    type: 'varchar',
    length: 255,
    comment: '密码',
    nullable: false,
    select: false,
  })
  password: string;

  @Column({
    type: 'enum',
    enum: ['admin', 'user'],
    comment: '角色',
    default: 'user',
    nullable: false,
  })
  // 角色
  role: 'admin' | 'user';

  @BeforeInsert() //在插入数据之前执行
  async encryptPwd() {
    this.password = await bcrypt.hashSync(this.password);
  }
}
